package cn.zwk.handler;

import cn.zwk.entity.AbstractItem;
import cn.zwk.entity.DataRow;
import cn.zwk.entity.MetricList;
import cn.zwk.entity.MultiRowItem;
import cn.zwk.entity.Snapshoot;
import cn.zwk.resolver.MetricListText;
import lombok.Data;

import java.util.ArrayList;
import java.util.List;

@Data
public class SummaryHandler extends MetricHandler {

    public SummaryHandler() {
        super.type = "summary";
    }

    @Override
    public MetricList buildMetric(MetricListText metricListText) {
        String[] lines = metricListText.getText().split("\n");
        StringBuilder annotationBuilder = new StringBuilder();
        int si = metricListText.getSi();

        // 构建annotation
        for (int i = 0; i < si; i++) {
            annotationBuilder.append(lines[i]);
            annotationBuilder.append("\n");
        }
        String countSpilt = metricListText.getName() + "_count";
        String sumSpilt = metricListText.getName() + "_sum";

        // 按_count分割，每个组形成一个MultiRowItem
        List<AbstractItem> items = new ArrayList<>();
        MultiRowItem currentItem = new MultiRowItem();
        List<DataRow> currentRows = new ArrayList<>();


        for (int i = si; i < lines.length; i++) {
            String line = lines[i].trim();
            if (line.isEmpty()) continue;

            DataRow dataRow = parseRow(line);
            if (dataRow == null) continue;

            // 检查是否是sum或count行
            if (line.contains(sumSpilt)) {
                currentItem.setSum(dataRow.getVal());
            } else if (line.contains(countSpilt)) {
                // 遇到_count行，当前MultiRowItem结束
                currentItem.setRows(currentRows);
                currentItem.setCount(dataRow.getVal());
                // 提取并设置label
                currentItem.setLabel(extractLabel(line));
                items.add(currentItem);
                currentItem = new MultiRowItem();
                currentRows = new ArrayList<>();
            }else {
                currentRows.add(dataRow);
            }
        }

        MetricList metricList = new MetricList();
        metricList.setAnnotation(annotationBuilder.toString());
        metricList.setName(metricListText.getName());
        metricList.setType(metricListText.getType());
        metricList.setItems(items);
        return metricList;
    }
    
    private String extractLabel(String line) {
        String[] parts = line.split("\\s+");
        if (parts.length > 0) {
            String metricPart = parts[0];
            // 提取标签部分作为label
            if (metricPart.contains("{")) {
                int start = metricPart.indexOf("{");
                int end = metricPart.indexOf("}", start);
                if (end > start) {
                    return metricPart.substring(start, end + 1);
                }
            }
        }
        return "";
    }


    @Override
    public void next(AbstractItem item) {
        if (item instanceof MultiRowItem multiRowItem) {
            List<DataRow> rows = multiRowItem.getRows();
            if (rows != null) {
                // 1. 计算新增的观测次数（整数）
                int newObservations = 1 + (int)(Math.random() * 5); // 1-5次新观测
                
                // 2. 更新count（整数）
                long newCount = (long)multiRowItem.getCount() + newObservations;
                multiRowItem.setCount(newCount);
                
                // 3. 更新sum（可以是小数）
                double avgValue = multiRowItem.getSum() / Math.max(1, multiRowItem.getCount());
                double newSum = multiRowItem.getSum() + (avgValue * newObservations * (1 + Math.random() * 0.5));
                multiRowItem.setSum(newSum);
                
                // 4. 更新quantile值（小幅波动）
                for (DataRow row : rows) {
                    if (row.getKey().contains("quantile")) {
                        // quantile值通常比较稳定，小幅波动
                        double currentVal = row.getVal();
                        double fluctuation = 0.95 + Math.random() * 0.1; // 0.95-1.05倍
                        row.setVal(currentVal * fluctuation);
                    }
                }
            }
        }
    }
}
